import { IVueI18n } from 'vue-i18n'
import { Middleware } from '@nuxt/types'

import { APP_LANGUAGE } from '@/enums/mutation-types'

const i18nMiddleware: Middleware = ({ isHMR, app, store, error }) => {
  if (isHMR) {
    // 是否是通过模块热替换，仅在客户端以dev模式
    return
  }
  const lang = app.$cookies.get('lang') || (app.i18n as IVueI18n).fallbackLocale
  if (!store.state.app.locales.includes(lang)) {
    return error({ message: 'This page could not be found.', statusCode: 404 })
  }
  (app.i18n as IVueI18n).locale = lang
  store.commit('app/' + APP_LANGUAGE, lang)
}

export default i18nMiddleware
